package com.sf.fy.uav.applet.utils;

import java.util.Arrays;
import java.util.List;

/**
 * @author 01430312
 */
public class GeoDistance {

    // 地球半径（单位：米）
    private static final double EARTH_RADIUS = 6371000;

    // 将经纬度转换为弧度
    private static double toRadians(double degree) {
        return degree * Math.PI / 180;
    }

    // 计算两点之间的距离
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double radLat1 = toRadians(lat1);
        double radLat2 = toRadians(lat2);
        double difference = toRadians(lat2 - lat1);
        double radLng = toRadians(lon2 - lon1);
        double a = Math.sin(difference / 2) * Math.sin(difference / 2) +
                Math.cos(radLat1) * Math.cos(radLat2) *
                        Math.sin(radLng / 2) * Math.sin(radLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return EARTH_RADIUS * c;
    }

    // 找到最近的点
    public static void findClosestPoint(double lat, double lon, List<LatLng> points) {
        System.out.println(System.currentTimeMillis());
        LatLng closestPoint = null;
        double minDistance = Double.MAX_VALUE;
        for (LatLng point : points) {
            double distance = calculateDistance(lat, lon, point.lat, point.lon);
            if (distance < minDistance) {
                minDistance = distance;
                closestPoint = point;
            }
        }
        if (closestPoint != null) {
            System.out.println("最近的点是: " + closestPoint + "，距离为：" + minDistance + " 米");
        }
        System.out.println(System.currentTimeMillis());
    }

    public static void main(String[] args) {
        List<LatLng> points = Arrays.asList(
                new LatLng(37.7833, -122.4167), // 山景城
                new LatLng(40.7128, -74.0060), // 纽约
                new LatLng(42.3584, -71.0644)  // 波士顿
        );

        // 假设我们要找的点是纽约的一个随机点
        findClosestPoint(40.7128, -74.0060, points);
    }

    static class LatLng {
        double lat;
        double lon;

        LatLng(double lat, double lon) {
            this.lat = lat;
            this.lon = lon;
        }

        @Override
        public String toString() {
            return "(" + lat + ", " + lon + ")";
        }
    }
}